package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 级联更新所有关联的数据
     * @param category
     */
   /* @Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1Categories'"),
            @CacheEvict(value = "category",key = "'getCatalogJson'")
    })*/
    @CacheEvict(value = "category",allEntries = true)
    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        if(!StringUtils.isEmpty(category.getName())){
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        }
    }
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }



    @Override
    public List<CategoryEntity> listWithTree() {
        //1, 查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2, 组装成父子的树形结构
        //2,1 找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map((menu)->{
                    menu.setChildren(getChidrens(menu,entities));
                    return menu;
                })
                .sorted((menu1,menu2)->{
                    return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());
        return level1Menus;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChidrens(CategoryEntity entity,List<CategoryEntity> entities){
        List<CategoryEntity> children = entities.stream()
                .filter(categoryEntity -> Objects.equals(categoryEntity.getParentCid(), entity.getCatId()))
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChidrens(categoryEntity,entities));
                    return categoryEntity;
                })
                .sorted((menu1,menu2)->{
                    return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());
        return children;
    }


    /*
     * 批量删除
     */
      @Override
    public void removeMenuByIds(List<Long> list) {

        //TODO  1.检查当前删除的菜单，是否被别的地方引用

        // 逻辑删除
        baseMapper.deleteBatchIds(list);
    }



    /**
     * 找到catelogId的完整路径：[父/子/孙]
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths=new ArrayList<>();

        List<Long> parentPath= findParentPath(catelogId,paths);
        Collections.reverse(parentPath);
        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1.收集当前节点id
        paths.add(catelogId);
         CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    @Cacheable(value = "category",key = "#root.methodName",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categories() {
        List<CategoryEntity> entities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;
    }


    @Cacheable(value = "category",key = "#root.methodName",sync = true)
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson(){
        System.out.println("查询数据库--------");

        /**
         * 1、将数据库的多次查询变为一次
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //1.查出所有1级分类
        List<CategoryEntity> level1Categories = getParentCid(selectList,0L);

        //2,封装数据
        Map<String, List<Catalog2Vo>> parent_cid = level1Categories.stream().collect(Collectors.toMap(
                k -> k.getCatId().toString(),
                v -> {
                    //1.查出2级分类
                    List<CategoryEntity> categoryEntities = getParentCid(selectList,v.getCatId());
                    List<Catalog2Vo> catalog2Vos = null;
                    if (categoryEntities !=null) {
                        catalog2Vos = categoryEntities.stream().map(l2 -> {
                            Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                            List<CategoryEntity> level3Catalog = getParentCid(selectList,l2.getCatId());
                            if(level3Catalog !=null){
                                List<Catalog2Vo.Catalog3Vo> catalog3Vos = level3Catalog.stream().map(l3 -> {
                                    Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                    return catalog3Vo;
                                }).collect(Collectors.toList());
                                catalog2Vo.setCatalog3List(catalog3Vos);
                            }
                            return catalog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catalog2Vos;
                }));
        return parent_cid;

    }
    //初始获取getCatalogJson()
    public Map<String, List<Catalog2Vo>> beginGetCatalogJson() {
        /**
         * 将数据库多次查询改为一次查询
         */
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //1.查出所有1级分类
        List<CategoryEntity> level1Categories = getLevel1Categories();

        //2,封装数据
        Map<String, List<Catalog2Vo>> parent_cid = level1Categories.stream().collect(Collectors.toMap(
                k -> k.getCatId().toString(),
                v -> {
                    //1.查出2级分类
                    List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
                    List<Catalog2Vo> catalog2Vos = null;
                    if (categoryEntities !=null) {
                        catalog2Vos = categoryEntities.stream().map(l2 -> {
                            Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                            List<CategoryEntity> level3Catalog = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                            if(level3Catalog !=null){
                                List<Catalog2Vo.Catalog3Vo> catalog3Vos = level3Catalog.stream().map(l3 -> {
                                    Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                    return catalog3Vo;
                                }).collect(Collectors.toList());
                                catalog2Vo.setCatalog3List(catalog3Vos);
                            }
                            return catalog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catalog2Vos;
                }));
        return parent_cid;
    }


    //TODO 产生堆外内存溢出：OutOfMemoryError: Java heap space
    //1 springboot2.0以后默认使用lettuce作为redis客户端,使用的是netty进行网络通信，
    //2 lettuce的BUG导致堆外内存溢出 -Xmx512m;netty如果没有指定堆外内存默认使用-Xmx512m;
    //3 -Dio.netty.maxDirectMemory进行设置
    //4 解决方案：不能使用-Dio.netty.maxDirectMemory只去调大堆外内存
    //4-1 升级lettuce客户端：2.5.0.RELEASE
    //4-2 切换使用jedis
    public Map<String, List<Catalog2Vo>> getCatalogJson2() {
        /**
         * 1空结果缓存:解决缓存穿透
         * 2设置过期时间(加随机值)：解决缓存雪崩
         * 3加锁：解决缓存击穿
         */
        //1加入缓存逻辑
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if(StringUtils.isEmpty(catalogJSON)){
            //缓存中没有,查询数据库
            System.out.println("缓存不命中......查询数据库......");
            Map<String, List<Catalog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLoak();
            return catalogJsonFromDb;
        }
        System.out.println("缓存命中......直接返回......");
        Map<String, List<Catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {});
        return result;
    }

    //从数据库中查询并封装分类数据(redisson分布式锁实现)
    /**
     * 缓存里面的数据如何和数据库保持一致
     * 缓存数据一致性
     * 1,双写模式
     * 2,失效模式
     * @return
     */
    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithRedissonLoak() {

        //1占redisson分布式锁
        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();
        System.out.println("获取分布式锁成功...");
        //2加锁成功,执行业务
        Map<String, List<Catalog2Vo>> dataFromDb;
        try{
            dataFromDb = getDataFromDb();
        }finally {
            lock.unlock();
        }
        return dataFromDb;
    }



    //从数据库中查询并封装分类数据(redis的setnx分布式锁)
    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithRedisLoak() {

        //1占setnx分布式锁
        String uuid = UUID.randomUUID().toString();
        //3设置过期时间
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        if(lock) {
            System.out.println("获取分布式锁成功...");
            //2加锁成功,执行业务
            Map<String, List<Catalog2Vo>> dataFromDb;
            try{
                dataFromDb = getDataFromDb();
            }finally {
                //删锁时得删自己的锁,使用UUID
                //redisTemplate.delete("lock");
                //获取值对比+对比成功删除=原子操作,Lua脚本解释
                //Lua脚本实现原子删锁
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);

                /*String lockValue= redisTemplate.opsForValue().get("lock");
                if(uuid.equals(lockValue)){
                    redisTemplate.delete("lock");
                }*/
            }

            return dataFromDb;
        }else {
            //加锁失败...休眠100ms重试
            System.out.println("获取分布式锁失败...");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLoak();//自旋的方式

        }

    }


    //从数据库中查询并封装分类数据(本地锁实现缓存问题)
    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDbWithLocalLoak() {

        //只要是同一把锁，就能锁住需要这个锁的所有线程
        //1,synchronized (this),springboot所有的组件在容器中都是单例的,
        // 但是this在分布式不友好,本地锁只能锁住当前进程,所以使用分布式锁
        //或者给方法加入synchronized

        //TODO  本地锁: synchronized(this)对象,JUC(Lock)
        synchronized (this){
            return getDataFromDb();
       }
    }

    //从数据库中查询并封装分类数据
    private Map<String, List<Catalog2Vo>> getDataFromDb() {
        //得到锁以后,需要在缓存再确定一次,没有才继续查询
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if(!StringUtils.isEmpty(catalogJSON)){
            //缓存不为空直接返回
            Map<String, List<Catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {});
            return result;
        }
        System.out.println("查询数据库--------");

        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //1.查出所有1级分类
        List<CategoryEntity> level1Categories = getParentCid(selectList,0L);

        //2,封装数据
        Map<String, List<Catalog2Vo>> parent_cid = level1Categories.stream().collect(Collectors.toMap(
                k -> k.getCatId().toString(),
                v -> {
                    //1.查出2级分类
                    List<CategoryEntity> categoryEntities = getParentCid(selectList,v.getCatId());
                    List<Catalog2Vo> catalog2Vos = null;
                    if (categoryEntities !=null) {
                        catalog2Vos = categoryEntities.stream().map(l2 -> {
                            Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                            List<CategoryEntity> level3Catalog = getParentCid(selectList,l2.getCatId());
                            if(level3Catalog !=null){
                                List<Catalog2Vo.Catalog3Vo> catalog3Vos = level3Catalog.stream().map(l3 -> {
                                    Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                    return catalog3Vo;
                                }).collect(Collectors.toList());
                                catalog2Vo.setCatalog3List(catalog3Vos);
                            }
                            return catalog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catalog2Vos;
                }));
        //查询到数据库之后，放入缓存,将对象转换为json放入缓存中
        redisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(parent_cid), 1, TimeUnit.DAYS);
        return parent_cid;
    }

    private List<CategoryEntity> getParentCid( List<CategoryEntity> selectList,Long parentCid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> Objects.equals(item.getParentCid(), parentCid)).collect(Collectors.toList());
        return collect;
        // return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }
}
